<!--
 * @Author: luojiajun
 * @Email: company.kachun@gmail.com
 * @Date: 2021-07-03 16:43:34
 * @FilePath: /src/views/service/application/edit.vue
 * @LastEditTime: 2021-07-27 17:58:29
 * @LastEditors: luojiajun
-->
<template>
    <div class="app-container app-height application-edit" :class="{ next: step == 2}">
        <div :class="{ 'bg-white': step == 1}">
            <div class="application-edit-form" v-show="step == 1">
                <div class="tree-title">接口服务基本信息</div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px">
                    <el-form-item label="API服务名称" prop="apiName">
                        <el-input v-model="ruleForm.apiName" placeholder="请输入接口名称"></el-input>
                    </el-form-item>

                    <el-form-item label="请求方式" prop="requestMethod">
                        <el-select v-model="ruleForm.requestMethod" placeholder="请选择请求方式">
                            <el-option label="GET" value="get"></el-option>
                            <el-option label="POST" value="post"></el-option>
                            <!-- <el-option label="PUT" value="put"></el-option>
                            <el-option label="DELETE" value="delete"></el-option> -->
                        </el-select>
                    </el-form-item>

                    <el-form-item label="接口描述" prop="apiDesc">
                        <el-input type="textarea" v-model="ruleForm.apiDesc" placeholder="请输入接口描述"></el-input>
                    </el-form-item>

                    <el-form-item label="数据来源" prop="source">
                        <el-radio-group v-model="ruleForm.source" @change="onChangeDataSource">
                            <el-radio label="1">数据仓库源表</el-radio>
                            <el-radio label="2">自定义SQL数据集</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item v-if="ruleForm.source == 1 && (!id || (id > 0 && ruleForm.apiBaseInfoId > 0))" label="数据仓库源表" prop="fields">
                        <select-dump @search="getTreeContent" is-table has-field :is-show-btn="false" :is-show-title="false" filter-permission :data="ruleForm" ref="treeDump"></select-dump>
                    </el-form-item>
                    
                    <el-form-item label="接口访问路径" prop="endpoint">
                        <!-- <span v-if="ruleForm.source == 1">{{ruleForm.url}}</span> -->
                        <el-input placeholder="请输入内容" v-model="ruleForm.endpoint" :readonly="ruleForm.source == 1">
                            <template slot="prepend">{{ruleForm.url}}</template>
                        </el-input>
                    </el-form-item>
                    
                    <template v-if="ruleForm.source != 1">
                        <div class="sql-code">
                            <div class="tree-title sql-code-title">编写SQL集</div>
                            <div class="sql-code-content">
                                <application-directory-tree></application-directory-tree>
                                <application-sql-collection ref="collection" :form="ruleForm" @success="onVerificationValid"></application-sql-collection>
                            </div>
                        </div>
                    </template>
                    
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" v-model="ruleForm.remark" placeholder="请输入备注"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" :loading="loading" @click="toNext('publish')" :disabled="loading || (ruleForm.source == 2 && !isValid)">发布</el-button>
                        <el-button type="primary" :loading="loading" @click="toNext('save')" :disabled="loading || (ruleForm.source == 2 && !isValid)">保存并退出</el-button>
                        <el-button @click="onCancel()">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <application-edit-test v-show="step == 2" :form="ruleForm" @prev="onBack" @cancel="onCancel"></application-edit-test>
        </div>
    </div>
</template>

<script>
import selectDump from "@/views/dataManagement/dataOverView/model/selectDump";
import { addInterface, editInterface, getInterfaceInfo } from "@/api/dataService/application"
import { getDomainName } from "@/api/common"
import ApplicationDirectoryTree from "@/views/service/application/components/ApplicationDirectoryTree"
import ApplicationSqlCollection from "@/views/service/application/components/ApplicationSqlCollection"
import ApplicationEditTest from "@/views/service/application/components/ApplicationEditTest"
import { mapGetters } from 'vuex'
import { isArray } from "@/utils/zkComm"

export default {
    name: "applicationEdit",
    components: {
        selectDump,
        ApplicationDirectoryTree,
        ApplicationSqlCollection,
        ApplicationEditTest
    },
    data() {
        let validateApiFields = (rule, value, callback) => {
            callback();
        };
        return {
            id: this.$route.params.id,
            loading: false,
            ruleForm: {
                apiBaseInfoId: 0,
                apiName: '',
                apiNameEn: '',
                requestMethod: '',
                source: '1',
                url: '', // process.env.VUE_APP_OPEN_API_URL,
                endpoint: '',
                apiDesc: '',
                remark: '',
                table: [],
                fields: [],
                dataSourceList:[],
                creator: ''
            },
            rules: {
                apiName: [
                    { required: true, message: '请输入接口服务名称', trigger: 'blur' },
                ],
                requestMethod: [
                    { required: true, message: '请选择请求方式', trigger: 'change' }
                ],
                source: [
                    { required: true, message: '请选择数据来源', trigger: 'change' }
                ],
                apiDesc: [
                    { required: true, message: '请填写接口描述', trigger: 'blur' }
                ],
                remark: [
                    { required: true, message: '请填写备注', trigger: 'blur' }
                ],
                fields: [
                    // { required: true, message: '请选择数据库源表和字段', trigger: 'blur' }
                    { required: true, validator: validateApiFields, trigger: 'blur' }
                ],
            },
            isValid: false,
            step: 1,
            apiDetailData: {}
        };
    },
    created() {
        this.getDomainName()
        
        this.ruleForm.creator = this.name
        if (this.id) {
            this.getInterfaceInfo();
        }
    },
    computed: {
        ...mapGetters(['name']),
    },
    methods: {
        getDomainName() {
            getDomainName().then((res) => {
                this.ruleForm.url = res.data

                console.log(this.ruleForm.url)
            }).catch(() => {})
        },
        getInterfaceInfo() {
            getInterfaceInfo(this.id).then(res => {
                if (res.code == 200) {
                    let data = res.data
                    this.ruleForm.apiBaseInfoId = data.id
                    this.ruleForm.apiName = data.apiName
                    this.ruleForm.apiNameEn = data.apiNameEn
                    this.ruleForm.apiDesc = data.apiDesc
                    this.ruleForm.source = data.dataSource
                    this.ruleForm.remark = data.remark
                    this.ruleForm.endpoint = data.requestPath.replace(this.ruleForm.url, '')
                    this.ruleForm.sqlStatement = data.sqlStatement
                    this.ruleForm.requestMethod = data.requestMethod
                    this.ruleForm.table = data.tableId
                    this.ruleForm.fields = data.tableFieldId
                    this.ruleForm.dataSourceList = data.dataSourceList
                    this.ruleForm.creator = data.createBy
                    
                    this.apiDetailData = Object.assign({}, {}, this.ruleForm)
                }
            }).catch(() => {})
        },
        submitForm(formName) {
            return new Promise((resolve) => {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        resolve(true)
                        return
                    }
                    resolve(false);
                });
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        toNext(action) {
            this.submitForm('ruleForm').then(async valid => {
                if (valid) {
                    if (!this.ruleForm.fields.length && this.ruleForm.source == 1) {
                        this.msgError('请选择数据库源表和字段')
                        return
                    }

                    if (action == 'save') await this.handleInterfaceSave()
                    if (action == 'publish') this.handleInterfacePublish()
                }
            })
        },
        onBack() {
            this.step = 1
            this.isValid = false
            if (this.$refs.collection) this.$refs.collection.resetForm()
        },
        onCancel() {
            this.deleteTagsView()
            this.$router.push('/service/application/mine')
        },
        deleteTagsView() {
            let view = { ...this.$route };
            this.$store.dispatch("tagsView/delView", view).then(() => {});
        },
        onChangeDataSource() {
            this.ruleForm.endpoint = ''
            this.ruleForm.table = []
            this.ruleForm.fields = []
            this.ruleForm.dataSourceList = []
        },
        getTreeContent(value){
            let table = value.data['table']
            let exclude = ['table', 'field']
            let endpoint = '', regx = /[A-Za-z]+/
            for (const key in value.data) {
                if (Object.hasOwnProperty.call(value.data, key)) {
                    const item = value.data[key];
                    if (!exclude.includes(key) && regx.test(item)) {
                        let matches = item.match(regx)
                        endpoint += `${matches[0]}/`
                    }
                }
            }

            let fields = value.fields.map(item => {
                return { id: item.id.toString(), fieldName: item.fieldName }
            })
            
            this.ruleForm.endpoint = (endpoint += table.value).toLocaleLowerCase()
            if (table && table.id) this.ruleForm.table = JSON.stringify([{tableName: table.value, id: table.id.toString()}])
            if (fields.length) this.ruleForm.fields = JSON.stringify(fields)
      	},
        async handleInterfaceSave(){
            if (this.loading) return

            this.loading = true

            this.handleInterfaceSavePromise().then(res => {
                this.deleteTagsView()
                this.$router.push({ path: '/service/application/mine' })
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },
        async handleInterfacePublish() {
            if (this.loading) return
            
            this.loading = true

            this.handleInterfaceSavePromise().then(apiBaseInfoId => {
                this.id = apiBaseInfoId
                this.ruleForm.apiBaseInfoId = apiBaseInfoId
                this.step = 2
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },
        handleInterfaceSavePromise() {
            return new Promise((resolve, reject) => {
                let postData = {
                    apiName: this.ruleForm.apiName,
                    apiNameEn: this.ruleForm.apiNameEn,
                    apiDesc: this.ruleForm.apiDesc,
                    // apiType: '',
                    // apiUpdateFrequency: '',
                    // apiVersionOut: '',
                    dataSource: this.ruleForm.source, // 数据来源 1-数据仓库源 2-自定义sql数据集
                    // groupId: '',
                    remark: this.ruleForm.remark,
                    requestMethod: this.ruleForm.requestMethod,
                    // requestParam: '',
                    // requestParamJson: '',
                    requestPath: this.ruleForm.endpoint,
                    // returnResultJson: '',
                    sqlStatement: '', // sql语句,数据源类型为 2 时，不能为空
                    tableFieldId: isArray(this.ruleForm.fields) ? JSON.stringify(this.ruleForm.fields) : this.ruleForm.fields, // 当数据源类型为2时，该字段值可以为空仓库表ID包含的字段ID
                    tableId: isArray(this.ruleForm.table) ? JSON.stringify(this.ruleForm.table) : this.ruleForm.table // 数据仓库源表ID，数据源为2时允许有多张表
                }

                if (this.ruleForm.source == 2) {
                    postData.sqlStatement = this.ruleForm.sqlStatement
                    // postData.tableFieldId = JSON.stringify([{'id':'8425','fieldName':'species_number'},{'id':'8426','fieldName':'drug_name'},{'id':8427,'fieldName':'notice_number'}])
                    // postData.tableId = JSON.stringify([{'tableName':'ods_nmpa_tcm_protect_drug_p_m_t','id':'491'}])
                }

                if (this.id > 0) {
                    postData.apiBaseInfoId = this.id
                    editInterface(postData).then(res => {
                        resolve(res.data)
                    }).catch(() => {
                        reject()
                    })
                } else {
                    addInterface(postData).then(res => {
                        resolve(res.data)
                    }).catch((error) => {
                        reject()
                    })
                }
            })
        },
        onVerificationValid(value) {
            this.isValid = value.valid
            
            if (!this.isValid) return
            
            if (value.sqlStatement)  this.ruleForm.sqlStatement = value.sqlStatement
            // if (value.tableId.length) this.ruleForm.table = JSON.stringify(value.tableId)
            // if (value.tableFieldId.length) this.ruleForm.fields = JSON.stringify(value.tableFieldId)
        },
        deleteTagsView() {
            let view = { ...this.$route }
            this.$store.dispatch('tagsView/delView', view).then(() => { })
        },
    }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/system/tree.scss";

.app-container {
    &.next {
        padding: 0;
        background: #efefef;
        box-shadow: none;
    }
}

.application-edit {
    padding: 20px;

    .tree-title {
        margin-top: 0;
    }

    .sql-code {
        display: flex;
        align-items: flex-start;
        margin-bottom: 26px;
        overflow: hidden;

        &-title {
            width: 110px;
            padding-right: 14px;
            flex-shrink: 0;
        }

        &-content {
            width: calc(100% - 114px);
            padding: 5px 0;
            display: flex;
            align-items: flex-start;
        }
    }

    ::v-deep {
        .el-form-item__label {
            text-align: right;
        }
    }
}
</style>
